﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using ProjectManagement.Domain.AutoMappings;
using NHibernate.Linq;
using ProjectManagement.Domain.Entities;

namespace ProjectManagement.Domain.Services
{
	public class ControllerActionRoleService
	{
		private static ISessionFactory factory = NHibernateHelper.CreateSessionFactory();
		private ISession session = factory.OpenSession();
		/// <summary>
		/// 根据角色id查询对应的权限Id列表
		/// </summary>
		/// <param name="id">角色Id</param>
		/// <returns>该角色对应的权限Id集合</returns>
		public IList<int> QueryControllerIdByRoleId(int id)
		{
			var controlleraciton=session.Query<ControllerActionRole>()
				.Where(c=>c.RoleID==id)
				.ToList();
			var list = new List<int>();
			foreach (var item in controlleraciton)
			{
				list.Add(item.ControllerActionID);
			}
			return list;
		}
		 /// <summary>
		 /// 保存角色与权限对应关系
		 /// </summary>
		 /// <param name="entity"></param>
		public void SaveConActRole(ControllerActionRole entity)
		{
			using (var trans = session.BeginTransaction())
			{
				session.Save(entity);
				trans.Commit();
				session.Flush();
			}
		}
		/// <summary>
		/// 根据roleId删除所有权限对应关系
		/// </summary>
		/// <param name="roleId"></param>
		public void DeleteConActRole(int roleId)
		{
			var con = session.Query<ControllerActionRole>()
				.Where(c => c.RoleID == roleId)
				.ToList();
			foreach (var item in con)
			{
				using (ITransaction trans = session.BeginTransaction())
				{
					session.Delete(item);
					trans.Commit();
				}
			}
		}
		/// <summary>
		/// 根据roleId和权限Id删除角色权限对应关系
		/// </summary>
		/// <param name="roleId"></param>
		/// <param name="conId"></param>
		public void DeleteConAcRole(int roleId, int conId)
		{
			var entity = session.Query<ControllerActionRole>()
				.Where(c => c.RoleID == roleId)
				.Where(c => c.ControllerActionID == conId)
				.First();
			using (ITransaction trans = session.BeginTransaction())
			{
				session.Delete(entity);
				trans.Commit();
			}
		}
	}
}
